package com.newgrand.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newgrand.mapper.UIPCommonMapper;
import com.newgrand.model.*;
import com.newgrand.utils.HRJdbcTemplate;
import com.newgrand.utils.i8util.EntityConverter;
import com.newgrand.utils.i8util.I8Request;
import com.newgrand.utils.i8util.StringHelper;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: zhanglixin
 * @Data: 2022/9/12 14:40
 * @Description: 组织数据保存
 */
@Service
public class OrgService {

    @Autowired
    private UIPCommonMapper uipCommonMapper;
    @Autowired
    private I8Request i8Request;

    @Autowired
    private EntityConverter entityConverter;

    @Autowired
    private HRJdbcTemplate jdbcTemplate;

    @Autowired
    private UipLog uipLog;

    //同步组织信息
    private static final String enterpriseformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"UnisocialCredit\":\"\",\"RegDt\":\"\",\"RegMoney\":\"\",\"Person\":\"\",\"RegionId\":\"\",\"EnterNatureId\":\"\",\"TradeTypeId\":\"5\",\"OTax\":\"\",\"TaxPayerType\":\"\",\"OAddr\":\"\",\"OZip\":\"\",\"ParentCompId\":\"\",\"OCfo\":\"\",\"FcNatural\":1,\"OTel\":\"\",\"OFax\":\"\",\"PhId\":\"\",\"NationId\":\"\",\"ProvinceId\":\"\",\"CityId\":\"\",\"key\":\"\"}}}";
    private static final String organizationformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"OCode\":\"\",\"OName\":\"\",\"Bopomofo\":\"\",\"CodeValue\":\"\",\"OrgType\":\"Y\",\"IsActive\":\"1\",\"CloseOrgDt\":\"\",\"EbDt\":\"\",\"EeDt\":\"\",\"GfiYear\":\"\",\"GfiCboo\":\"\",\"OrgOwner\":\"\",\"IsInner\":1,\"OMemo\":\"\",\"OrgNatura\":\"\",\"BeloCuid\":\"\",\"RelProject\":\"\",\"BelongDept\":\"\",\"WeChatId\":\"\",\"IsColleague\":\"1\",\"user_mdmcode\":\"\",\"user_sap\":\"\",\"user_nc\":\"\",\"PhId\":\"\",\"OrgIndex\":\"\",\"OrgLabel\":\"\",\"SystemOrgType\":\"ORG\",\"DataFlag\":\"1\",\"attrcode14\":\"\",\"attrcode18\":\"\",\"attrcode23\":\"\",\"attrcode30\":\"\",\"attrcode45\":\"\",\"attrcode46\":\"\",\"attrcode47\":\"\",\"IsWeChat\":\"\",\"IsNfcShow\":\"\",\"IsEnd\":\"\",\"IsGroup\":\"\",\"UnisocialCredit\":\"\",\"RegDt\":\"\",\"RegMoney\":\"\",\"Person\":\"\",\"RegionId\":\"\",\"EnterNatureId\":\"\",\"TradeTypeId\":\"\",\"OTax\":\"\",\"TaxPayerType\":\"\",\"OAddr\":\"\",\"OZip\":\"\",\"ParentCompId\":\"\",\"OCfo\":\"\",\"FcNatural\":1,\"OTel\":\"\",\"OFax\":\"\",\"NationId\":\"\",\"ProvinceId\":\"\",\"CityId\":\"\",\"key\":\"\"}}}";
    //同步部门信息
    private static final String organizationformData1 = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"OCode\":\"\",\"OName\":\"\",\"Bopomofo\":\"\",\"CodeValue\":\"\",\"OrgType\":\"N\",\"IsActive\":\"1\",\"CloseOrgDt\":\"\",\"EbDt\":\"\",\"EeDt\":\"\",\"GfiYear\":\"\",\"GfiCboo\":\"\",\"OrgOwner\":\"\",\"OMemo\":\"\",\"OrgNatura\":\"\",\"BeloCuid\":\"\",\"RelProject\":\"\",\"BelongDept\":\"\",\"WeChatId\":\"\",\"IsColleague\":\"1\",\"user_mdmcode\":\"\",\"user_sap\":\"\",\"user_nc\":\"\",\"IsInner\":0,\"PhId\":\"\",\"OrgIndex\":\"\",\"OrgLabel\":\"\",\"SystemOrgType\":\"DEPT\",\"DataFlag\":\"1\",\"IsWeChat\":\"\",\"IsNfcShow\":\"\",\"IsEnd\":\"\",\"attrcode46\":\"\",\"IsGroup\":\"\",\"ParentOrgId\":\"\",\"EmpCode\":\"\",\"OTax\":\"\",\"DeptAttr\":\"\",\"key\":\"\"}}}";
    private static final String enterpriseformData1 = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"UnisocialCredit\":\"\",\"RegDt\":\"\",\"RegMoney\":\"\",\"Person\":\"\",\"RegionId\":\"\",\"EnterNatureId\":\"\",\"TradeTypeId\":\"\",\"OTax\":\"\",\"TaxPayerType\":\"\",\"OAddr\":\"\",\"OZip\":\"\",\"ParentCompId\":\"\",\"OCfo\":\"\",\"FcNatural\":1,\"OTel\":\"\",\"OFax\":\"\",\"PhId\":\"\",\"NationId\":\"\",\"ProvinceId\":\"\",\"CityId\":\"\",\"key\":\"\"}}}";

    private static final String RelatLgPhid = "146220711000001";
    private static final String Relat18Phid = "146220711000003";
    private static final String Relat23Phid = "146220711000002";
    private static final String Relat14Phid = "330441632000001";//财务


    /**
     * 用于同步数据用
     */
    @Scheduled(cron = "0 0 */12 * * ?")
    public void SyncData(){
        try {
            List<Map<String, Object>> orgList = jdbcTemplate.GetJdbcTemplate().
                    queryForList("select id as \"id\",description as \"description\",qywxsjbh as \"qywxsjbh\",child as \"child\",deletesign as \"deletesign\",code as \"code\",is_org as \"is_org\" from TUO2_QYWX order by child");
            if(orgList.size()>0){
                int count = orgList.size();
                uipLog.info("orgsync", "同步组织","开始同步..");
                for(int i=0;i<count;i++){
                    Map<String,Object> org = orgList.get(i);
                    OrgInfo orgInfo = new OrgInfo();

                    String id = StringHelper.nullToEmpty(org.get("id"));//勤科id
                    String description = StringHelper.nullToEmpty(org.get("description"));//勤科名称
                    String qywxsjbh = StringHelper.nullToEmpty(org.get("qywxsjbh"));//勤科 上级id
                    String child = StringHelper.nullToEmpty(org.get("child"));//勤科 编码 会变
                    String deletesign = StringHelper.nullToEmpty(org.get("deletesign"));//勤科 机构状态  1表示隐藏、0表示在用
                    String is_org = StringHelper.nullToEmpty(org.get("is_org"));//勤科 是否组织  1组织

                    orgInfo.oname = description;
                    orgInfo.ifcorp = "1".equals(is_org)?"Y":"N";
                    orgInfo.isactive = "0".equals(deletesign)?"1":"0";
                    orgInfo.orgtype = "1".equals(is_org)?"Y":"N";

                    List<Map<String, Object>> listParent =uipCommonMapper.dynamicSql("select phid as \"phid\",parent_orgid as \"parent_orgid\",ocode as \"ocode\" from fg_orglist where user_qkhr='"+qywxsjbh+"'");
                    String parentOrg = "";
                    String parent_orgid = "";
                    String parentOcode = "";
                    if (listParent.size() > 0) {
                        //判断上级是部门还是组织
                        //uipLog.info("orgsync", "同步组织","map:"+JSON.toJSONString(listParent.get(0)));
                        //上级如果是部门  那上级的parent_orgid就是归属组织phid  上级如果是组织  那上级的phid就是归属组织phid
                        parentOrg = listParent.get(0).get("phid").toString();
                        parent_orgid = listParent.get(0).get("parent_orgid").toString();
                        parentOcode = listParent.get(0).get("ocode").toString();
                        orgInfo.parentocode = parentOcode;
                        if(!StringUtils.isEmpty(parent_orgid)&&!"0".equals(parent_orgid)){
                            parentOrg = parent_orgid;
                        }
                    } else {
                        uipLog.info("orgsync", "同步组织","id:"+id+",名称:"+description+",上级,"+qywxsjbh+"不存在");
                        continue;//上级不存在
                    }
                    //uipLog.info("orgsync", "同步组织","22222index:"+i);
                    List<Map<String, Object>> listOrg =uipCommonMapper.dynamicSql("select phid as \"phid\",parent_orgid as \"parent_orgid\",ocode as \"ocode\" from fg_orglist where user_qkhr='"+id+"'");
                    if (listOrg.size() > 0)
                    {
                        //当前数据存在  就用i8自己的编码
                        String ocode = listOrg.get(0).get("ocode").toString();
                        orgInfo.ocode = ocode;
                    }
                    else
                    {
                        //新增处理
                        //不存在的时候编码生成规则
                        if("1".equals(is_org)){
                            orgInfo.ocode = id.substring(id.length() - 4);
                        }else{
                            //上级编码+勤科id的后三位作为i8的编码
                            orgInfo.ocode = parentOcode+"."+ id.substring(id.length() - 4);
                        }
                    }

                    CodeMsg codeMsg = SaveOrg(orgInfo);
                    if("S".equals(codeMsg.code)){
                        //更新编码
                        uipCommonMapper.dynamicSql("update fg_orglist set user_qkhr='"+id+"' where ocode='"+orgInfo.ocode+"'");
                    }
                    uipLog.info("orgsync", "同步组织","id:"+id+",名称:"+description+",同步返回:"+JSON.toJSONString(codeMsg));

                }
                uipLog.info("orgsync", "同步组织","结束同步..");
            }
        }catch (Exception ex){
            uipLog.error("orgsync", "同步组织","同步异常:"+ex.getMessage());
        }

    }


    public CodeMsg SaveOrg(OrgInfo orgInfo){
        CodeMsg codeMsg = new CodeMsg();
        try
        {
            List<Map<String, Object>> listParent =uipCommonMapper.dynamicSql("select phid as \"phid\",parent_orgid as \"parent_orgid\" from fg_orglist where ocode='"+orgInfo.parentocode+"'");
            String parentOrg = "";
            if (listParent.size() > 0) {
                //判断上级是部门还是组织
                //上级如果是部门  那上级的parent_orgid就是归属组织phid  上级如果是组织  那上级的phid就是归属组织phid
                parentOrg = listParent.get(0).get("phid").toString();
                String parent_orgid = listParent.get(0).get("parent_orgid").toString();
                if(!StringUtils.isEmpty(parent_orgid)&&!"0".equals(parent_orgid)){
                    parentOrg = parent_orgid;
                }
            } else {
                codeMsg.code = "E";
                codeMsg.msg = "上级组织不存在";
                return codeMsg;
            }
            String systemOrgType = "";
            String orgType = "";
            if ("Y".equals(orgInfo.orgtype)) {
                systemOrgType = "ORG";
                orgType = "Y";
            } else {
                systemOrgType = "DEPT";
                orgType = "N";
            }
            //所属单元
            String BeloCuid = "";
            List<Map<String, Object>> listBelo =uipCommonMapper.dynamicSql("select belongto_cuid as \"belongto_cuid\" from fg_orgrelatitem where org_id='"+parentOrg+"'");
            if (listBelo.size() > 0) {
                BeloCuid = StringHelper.nullToEmpty(listBelo.get(0).get("belongto_cuid"));
            }
            List<Map<String, Object>> listOcode =uipCommonMapper.dynamicSql("select phid as \"phid\" from fg_orglist where ocode='"+orgInfo.ocode+"'");

            if (listOcode.size()==0) {//新增
                List<NameValuePair> urlParameters = new ArrayList<>();
                HashMap<String, Object> mapInfo = new HashMap<>();
                mapInfo.put("OCode", orgInfo.ocode);
                mapInfo.put("OName", orgInfo.oname);
                mapInfo.put("SystemOrgType", systemOrgType);
                mapInfo.put("OrgType", orgType);
                mapInfo.put("UnisocialCredit", orgInfo.unisocialcredit);

                if(!StringUtils.isEmpty(orgInfo.orgnatura)){
                    //添加组织性质  主要用于区分 法人单位 利润中心 成本中心
                    mapInfo.put("OrgNatura", orgInfo.orgnatura);
                }

                if ("DEPT".equals(systemOrgType)) {//部门
                    mapInfo.put("ParentOrgId", parentOrg);
                    urlParameters.add(new BasicNameValuePair("enterpriseformData", enterpriseformData1));
                    urlParameters.add(new BasicNameValuePair("orgtype", "N"));
                    urlParameters.add(new BasicNameValuePair("organizationformData", entityConverter.SetFieldForm(organizationformData1, mapInfo)));
                    urlParameters.add(new BasicNameValuePair("orgattrgridData", "")); //47 单元（）
                } else {//组织
                    //统一社会信用代码
                    HashMap<String, Object> entMap = new HashMap<>();
                    entMap.put("UnisocialCredit", orgInfo.unisocialcredit);

                    urlParameters.add(new BasicNameValuePair("enterpriseformData", entityConverter.SetFieldForm(enterpriseformData, entMap)));
                    urlParameters.add(new BasicNameValuePair("orgtype", "Y"));
                    urlParameters.add(new BasicNameValuePair("organizationformData", entityConverter.SetFieldForm(organizationformData, mapInfo)));
                    urlParameters.add(new BasicNameValuePair("orgattrgridData", "lg,18,23,30,")); //47 单元（）
                }
                urlParameters.add(new BasicNameValuePair("attachGuid", ""));
                String i8rv = i8Request.PostFormSync("/DMC/Org/Organization/save", urlParameters);
                uipLog.info("orgsync", "同步组织","编码:"+orgInfo.ocode+",名称:"+orgInfo.oname+",上级编码:"+orgInfo.parentocode+",归属组织:"+parentOrg+",i8返回:"+i8rv);
                if (StringUtils.isEmpty(i8rv)) {
                    codeMsg.code = "E";
                    codeMsg.msg = "调用i8的保存组织信息接口返回为空";
                    return codeMsg;
                }
                JSONObject i8rvJson = JSONObject.parseObject(i8rv);
                if (i8rvJson.getString("Status").equals("success")) {
                    String newphId = i8rvJson.getJSONArray("KeyCodes").getString(0);

                    //添加树节点
                    OrgModel orgModel = new OrgModel();
                    orgModel.ocode = orgInfo.ocode;
                    orgModel.oname = orgInfo.oname;
                    orgModel.parentocode = orgInfo.parentocode;
                    orgModel.codevalue = orgInfo.codevalue;
                    orgModel.isactive = "1";
                    orgModel.orgtype = systemOrgType;
                    orgModel.curPhId = BeloCuid;
                    orgModel.parentPhId = parentOrg;

                    AddTreeMsg addTreeMsg = AddTree(orgModel, newphId, "lg", RelatLgPhid);
                    uipLog.info("orgsync", "同步lg组织关系树","编码:"+orgInfo.ocode+",名称:"+orgInfo.oname+",上级编码:"+orgInfo.parentocode+",归属组织:"+parentOrg+",i8返回:"+addTreeMsg.msg);
                    addTreeMsg = AddTree(orgModel, newphId, "18", Relat18Phid);
                    uipLog.info("orgsync", "同步18组织关系树","编码:"+orgInfo.ocode+",名称:"+orgInfo.oname+",上级编码:"+orgInfo.parentocode+",归属组织:"+parentOrg+",i8返回:"+addTreeMsg.msg);
                    addTreeMsg = AddTree(orgModel, newphId, "23", Relat23Phid);
                    uipLog.info("orgsync", "同步23组织关系树","编码:"+orgInfo.ocode+",名称:"+orgInfo.oname+",上级编码:"+orgInfo.parentocode+",归属组织:"+parentOrg+",i8返回:"+addTreeMsg.msg);
                    codeMsg.code = "S";
                    codeMsg.msg = "保存成功";
                    return codeMsg;
                } else {
                    codeMsg.code = "E";
                    codeMsg.msg = "保存组织信息失败:"+i8rv;
                    return codeMsg;
                }
            } else {//更新
                //如果是组织数据  需要更新往来单位名称
                if ("ORG".equals(systemOrgType)) {
                    uipCommonMapper.dynamicSql("update FG3_ENTERPRISE set COMPNAME='"+orgInfo.oname+"' where COMPNO='"+orgInfo.ocode+"'");
                }

                String parent_orgid = "0";
                if ("N".equals(orgInfo.orgtype)) {
                    parent_orgid = parentOrg;
                }
                Date now = new Date();
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = bartDateFormat.format(now);
                uipCommonMapper.dynamicSql("update fg_orglist set oname='"+orgInfo.oname+"',ng_update_dt=to_date('"+nowTime+"','yyyy-MM-dd hh24:mi:ss'),system_orgType ='"+systemOrgType+"',parent_orgid='"+parent_orgid+"',isActive='"+orgInfo.isactive+"' where ocode='"+orgInfo.ocode+"'");

                if("1".equals(orgInfo.isactive)){
                    //添加树节点
                    OrgModel orgModel = new OrgModel();
                    orgModel.ocode = orgInfo.ocode;
                    orgModel.oname = orgInfo.oname;
                    orgModel.parentocode = orgInfo.parentocode;
                    orgModel.codevalue = orgInfo.codevalue;
                    orgModel.isactive = "1";
                    orgModel.orgtype = systemOrgType;
                    orgModel.curPhId = BeloCuid;
                    orgModel.parentPhId = parentOrg;
                    String orgPhid1 = StringHelper.nullToEmpty(listOcode.get(0).get("phid"));
                    AddTreeMsg addTreeMsg = AddTree(orgModel, orgPhid1, "lg", RelatLgPhid);
                    uipLog.info("orgsync", "同步lg组织关系树","编码:"+orgInfo.ocode+",名称:"+orgInfo.oname+",上级编码:"+orgInfo.parentocode+",归属组织:"+parentOrg+",i8返回:"+addTreeMsg.msg);
                    AddTree(orgModel, orgPhid1, "18", Relat18Phid);
                    uipLog.info("orgsync", "同步18组织关系树","编码:"+orgInfo.ocode+",名称:"+orgInfo.oname+",上级编码:"+orgInfo.parentocode+",归属组织:"+parentOrg+",i8返回:"+addTreeMsg.msg);
                    AddTree(orgModel, orgPhid1, "23", Relat23Phid);
                    uipLog.info("orgsync", "同步23组织关系树","编码:"+orgInfo.ocode+",名称:"+orgInfo.oname+",上级编码:"+orgInfo.parentocode+",归属组织:"+parentOrg+",i8返回:"+addTreeMsg.msg);
                }else{
                    //移除组织树上的节点
                    uipCommonMapper.dynamicSql("delete fg_orgrelatitem where ocode='"+orgInfo.ocode+"'");
                }


                codeMsg.code = "S";
                codeMsg.msg = "修改成功";
            }
        }catch (Exception ex)
        {
            codeMsg.code = "E";
            codeMsg.msg = "接口异常:"+ex.getMessage();
        }
        return codeMsg;
    }


    /**
     * 功能描述: 更新不同的树结构,返回出错消息
     *
     * @Param: [desc2, parentcode]
     * @Return: java.lang.String
     * @Author: xienb
     * @Date: 2020/12/3
     */
    private AddTreeMsg AddTree(OrgModel model, String orgPhid, String relatid, String relatPhid) {
        AddTreeMsg addTreeMsg = new AddTreeMsg();
        try {
            TreeNode treeNode = new TreeNode();
            treeNode.OCode = model.ocode;
            treeNode.OrgId = orgPhid;
            treeNode.ParentOrg = model.parentocode;
            treeNode.OName = model.oname;
            treeNode.OrgType = model.orgtype;
            treeNode.OrderType = model.orgtype;
            treeNode.AttrCode = relatid;
            treeNode.RelatId = relatid;
            treeNode.PhId = relatPhid;
            treeNode.curPhId = model.curPhId;
            //先判断上级是否已经同步到组织表里面了
            List<Map<String, Object>> list = uipCommonMapper.dynamicSql("select count(*) from fg_orglist where ocode='"+model.parentocode+"'");
            if (list.size() > 0) {
                //判断上级组织是否已经在组织关系树上
                List<Map<String, Object>> list1 = uipCommonMapper.dynamicSql("select count(1) from fg_orgrelatitem where ocode ='"+model.parentocode+"' and relatid='"+treeNode.RelatId+"'");
                if (list1.size() > 0) {
                    //判断当前节点是否在关系树上
                    List<Map<String, Object>> list2 = uipCommonMapper.dynamicSql("select * from fg_orgrelatitem where relatid ='"+treeNode.RelatId+"' and ocode='"+treeNode.OCode+"'");
                    if (list2.size() == 0) {
                        addTreeMsg = AddTreeNode(treeNode);
                    } else if (list2.size() == 1) {
                        //判断上级是否发生变化
                        List<Map<String, Object>> list3 = uipCommonMapper.dynamicSql("select count(fo.phid) from (select phid from fg_orglist where ocode='"+treeNode.ParentOrg+"') fo where fo.phid=(select parent_orgid from fg_orgrelatitem where ocode='"+treeNode.OCode+"' and relatid='"+treeNode.RelatId+"')");
                        if (list3.size() > 0) {
                            addTreeMsg.code = "success";
                            addTreeMsg.msg = "无需修改树结构";
                        } else {
                            addTreeMsg.code = "success";
                            addTreeMsg.msg = "树结构有发生变化,涉及到权限问题,需前台手工调整树节点";
                        }
                    } else {
                        addTreeMsg.code = "error";
                        addTreeMsg.msg = "表出现多条记录";
                    }
                } else {
                    addTreeMsg.code = "error";
                    addTreeMsg.msg = "请先同步上级组织关系树数据";
                }
            } else {
                addTreeMsg.code = "error";
                addTreeMsg.msg = "请先同步上级组织数据";
            }
            return addTreeMsg;
        } catch (Exception ex) {
            ex.printStackTrace();
            addTreeMsg.code = "error";
            addTreeMsg.msg = "AddTree方法出现异常:" + ex.getMessage();
            return addTreeMsg;
        }
    }

    /**
     * 功能描述: 更新树结点数据
     *
     * @Param: [treeNode]
     * @Return: com.newgrand.secdev.domain.AddTreeMsg
     * @Author: xienb
     * @Date: 2020/12/4
     */
    private AddTreeMsg AddTreeNode(TreeNode treeNode) {
        AddTreeMsg addTreeMsg = new AddTreeMsg();
        try {
            //查上级关系树的相关数据
            //System.err.println(treeNode.ParentOrg + "/" + treeNode.RelatId);
            List<Map<String, Object>> list = uipCommonMapper.dynamicSql("select relatindex as \"relatindex\",org_id as \"orgid\",ocode as \"ocode\" from fg_orgrelatitem where ocode ='"+treeNode.ParentOrg+"' and relatid ='"+treeNode.RelatId+"'");
            if (list.size() > 0) {
                //uipLog.info("orgsync", "同步组织关系树","11111111111");
                String relatindex = list.get(0).get("relatindex").toString().trim();//层级
                String parentPhid = list.get(0).get("orgid").toString().trim();//父级phid
                String parentOCode = list.get(0).get("ocode").toString().trim();//父级编码
                //uipLog.info("orgsync", "同步组织关系树","22222222222");
                if (relatindex.length() > 0) {
                    String isql = "select count(1) as \"idx\" from fg_orgrelatitem where relatid = '" + treeNode.RelatId + "' and relatindex like '" + relatindex + "%' and parent_orgid = '" + parentPhid + "'";
                    List<Map<String, Object>> listIndex = uipCommonMapper.dynamicSql(isql);
                    Integer index = Integer.parseInt(StringHelper.nullToEmpty(listIndex.get(0).get("idx")));
                    HashMap<String, Object> orgrelatfromDataDict = new HashMap<>();
                    ArrayList<HashMap<String, Object>> nodedataDictList = new ArrayList<>();
                    HashMap<String, Object> nodedataDict = new HashMap<>();

                    orgrelatfromDataDict.put("RelatId", treeNode.RelatId);
                    orgrelatfromDataDict.put("AttrCode", treeNode.AttrCode);
                    orgrelatfromDataDict.put("PhId", treeNode.PhId);//fg_orgrelat 表的phid
                    orgrelatfromDataDict.put("key", treeNode.PhId);//fg_orgrelat 表的phid
                    //uipLog.info("orgsync", "同步组织关系树","3333333333");
                    nodedataDict.put("OCode", treeNode.OCode);//组织编码
                    nodedataDict.put("OName", treeNode.OName);//组织名称
                    nodedataDict.put("text", "(" + treeNode.OCode + ")" + treeNode.OName);//(组织编码)组织名称
                    nodedataDict.put("ParentOrg", parentOCode);//父级组织编码
                    nodedataDict.put("RelaIndex", relatindex + treeNode.OrgId + "-");
                    nodedataDict.put("index", index);
                    nodedataDict.put("OrderType", treeNode.OrderType);
                    nodedataDict.put("OrgType", treeNode.OrgType);
                    nodedataDict.put("OrgId", treeNode.OrgId);//组织phid
                    nodedataDict.put("ParentOrgId", parentPhid);//父级组织phid
                    nodedataDict.put("parentId", parentPhid);//父级组织phid
                    nodedataDict.put("depth", "");
                    nodedataDict.put("BelongCuid", treeNode.curPhId);//所属单元
                    if (treeNode.OrgType.equals("DEPT")) {
                        nodedataDict.put("SystemOrgType", "DEPT");//组织ORG,部门DEPT
                    } else {
                        nodedataDict.put("SystemOrgType", "ORG");//组织ORG,部门DEPT
                    }
                    nodedataDictList.add(nodedataDict);
                    String orgrelatfromStr = "{\"form\":{\"key\":\"PhId\",\"modifiedRow\":{\"RelatId\":\"\",\"RelatName\":\"\",\"EbDt\":\"\",\"EeDt\":\"\",\"Descript\":\"\",\"AttrCode\":\"\",\"ShowModel\":\"Y\",\"PhId\":\"\",\"key\":\"\"}}}";
                    String nodedataStr = "[{\"row\":{\"PhId\":\"\",\"RelatId\":\"\",\"SystemOrgType\":\"CU\",\"OCode\":\"\",\"ParentOrg\":\"\",\"RelaIndex\":\"\",\"index\":\"\",\"OrderType\":\"\",\"OrgId\":\"\",\"ParentOrgId\":\"\",\"NgRecordVer\":0,\"OName\":\"\",\"text\":\"\",\"IfCorp\":\"\",\"Selected\":\"\",\"DeptBelongOrg\":\"\",\"IsEnd\":\"\",\"OrgType\":\"\",\"BelongCuid\":\"\",\"parentId\":\"\",\"depth\":\"\",\"expanded\":false,\"expandable\":true,\"checked\":null,\"leaf\":true,\"cls\":\"\",\"iconCls\":\"no-icon\",\"icon\":\"\",\"root\":false,\"isLast\":true,\"isFirst\":false,\"allowDrop\":true,\"allowDrag\":true,\"loaded\":false,\"loading\":false,\"href\":\"\",\"hrefTarget\":\"\",\"qtip\":\"\",\"qtitle\":\"\",\"qshowDelay\":0,\"children\":null,\"key\":null}}]";

                    List<NameValuePair> urlParameters = new ArrayList<>();
                    urlParameters.add(new BasicNameValuePair("orgrelatfromData", entityConverter.SetFieldForm(orgrelatfromStr, orgrelatfromDataDict)));
                    urlParameters.add(new BasicNameValuePair("nodedata", entityConverter.SetTableRow(nodedataStr, nodedataDictList)));
                    String i8rv = i8Request.PostFormSync("/DMC/Org/OrgRelat/save", urlParameters);
                    //uipLog.info("orgsync", "同步组织关系树","保存返回:"+i8rv);
                    if (StringUtils.isEmpty(i8rv)) {
                        addTreeMsg.code = "error";
                        addTreeMsg.msg = "添加树结构请求异常";
                    } else {
                        JSONObject i8rvJson = JSON.parseObject(i8rv);
                        if (i8rvJson.getString("Status").equals("success")) {
                            addTreeMsg.code = "success";
                            addTreeMsg.msg = "添加树结构成功";
                        } else {
                            addTreeMsg.code = "error";
                            addTreeMsg.msg = "添加树结构失败:" + i8rvJson.getString("Msg");
                        }
                    }
                }
            }
            return addTreeMsg;
        } catch (Exception ex) {
            ex.printStackTrace();
            addTreeMsg.code = "error";
            addTreeMsg.msg = "AddTreeNode方法出现异常:" + ex.getMessage();
            return addTreeMsg;
        }
    }

}